import {
  AfterViewInit,
  ChangeDetectionStrategy,
  ChangeDetectorRef,
  Component,
  Input,
  OnDestroy,
  OnInit,
  TemplateRef,
  ViewEncapsulation,
} from '@angular/core';
import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
import { TypeUtils } from '../core/utils/type';
import { LvListItemLayout } from '../core/types';
import { ListItemComponent } from './list-item.component';

@Component({
  selector: 'lv-list-item-meta, [lv-list-item-meta]',
  templateUrl: './list-item-meta.component.html',
  encapsulation: ViewEncapsulation.None,
  changeDetection: ChangeDetectionStrategy.OnPush,
  host: {
    class: 'lv-list-item-meta',
    '[class.lv-list-item-meta-only-title]': 'lvTitle && !lvDescription',
  },
})
export class ListItemMetaComponent implements OnInit, AfterViewInit, OnDestroy {
  @Input() lvDataSource: any;
  @Input() lvTitle: string | TemplateRef<void>;
  @Input() lvAvatar: string | TemplateRef<void>;
  @Input() lvDescription: string | TemplateRef<void>;

  typeUtils = TypeUtils;
  extra: TemplateRef<void>;
  actions: Array<TemplateRef<void>> = [];
  itemLayout: LvListItemLayout = 'horizontal';

  private destroy$ = new Subject<void>();

  constructor(
    private parentCom: ListItemComponent,
    private cdr: ChangeDetectorRef,
  ) {}

  ngOnDestroy(): void {
    this.destroy$.next();
    this.destroy$.complete();
  }

  ngOnInit(): void {
    this.actions = this.parentCom?.lvActions;
    this.extra = this.parentCom?.lvExtra;
  }

  ngAfterViewInit(): void {
    this.parentCom?.layout$.pipe(takeUntil(this.destroy$)).subscribe((res): void => {
      this.itemLayout = res;
      this.cdr.markForCheck();
    });
  }
}
